// 200. 岛屿数量
var numIslands = function(grid) {
    let n = grid.length, m = grid[0].length;
    let res = 0;
    for(let i = 0; i<n; i++){
        for(let j = 0; j<m; j++) {
            if(grid[i][j] ==='1'){
                res++;
                dfs(grid, i, j);
            }
        }
    }
    function dfs(grid, i, j){
        if(i<0 ||j<0 || i>=n || j>=m || grid[i][j] === '0') return;
        grid[i][j] = '0';
        dfs(grid, i-1, j);
        dfs(grid, i+1, j);
        dfs(grid, i, j-1);
        dfs(grid, i, j+1);
    }
    return res;
};


// 695. 岛屿的最大面积
var maxAreaOfIsland = function (grid) {
    let res = 0;
    const rows = grid.length;
    const cols = grid[0].length;
    if (rows == 0) return res;
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (grid[i][j] == "1") {
                let current = dfs(grid, i, j, rows, cols);
                res = Math.max(res, current);
            }
        }
    }
    return res;
};

function dfs(grid, i, j, rows, cols) {
    if (i < 0 || i > rows - 1 || j < 0 || j > cols - 1 || grid[i][j] == "0") return 0;
    grid[i][j] = "0";
    return 1 + dfs(grid, i - 1, j, rows, cols)
        + dfs(grid, i + 1, j, rows, cols)
        + dfs(grid, i, j - 1, rows, cols)
        + dfs(grid, i, j + 1, rows, cols);
}